package com.example.aitasks.web;

import com.example.aitasks.model.TaskConfig;
import com.example.aitasks.model.TaskResult;
import com.example.aitasks.repo.TaskConfigRepository;
import com.example.aitasks.repo.TaskResultRepository;
import com.example.aitasks.service.TaskRunnerService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/tasks")
public class TaskController {
    private final TaskConfigRepository configRepo;
    private final TaskResultRepository resultRepo;
    private final TaskRunnerService runner;

    public TaskController(TaskConfigRepository configRepo, TaskResultRepository resultRepo, TaskRunnerService runner) {
        this.configRepo = configRepo;
        this.resultRepo = resultRepo;
        this.runner = runner;
    }

    @GetMapping
    public List<TaskConfig> list() {
        return configRepo.findAll();
    }

    @PostMapping
    public TaskConfig create(@Valid @RequestBody TaskConfig t) {
        return configRepo.save(t);
    }

    @PutMapping("/{id}")
    public TaskConfig update(@PathVariable Long id, @Valid @RequestBody TaskConfig t) {
        t.setId(id);
        return configRepo.save(t);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) {
        configRepo.deleteById(id);
    }

    @PostMapping("/{id}/run")
    public TaskResult run(@PathVariable Long id) {
        return runner.runOnce(id);
    }

    @GetMapping("/{id}/results")
    public List<TaskResult> results(@PathVariable Long id) {
        return resultRepo.findTop10ByTaskIdOrderByRunAtDesc(id);
    }
}
